#include "gpio.h"



int gpio_export(GPIO * gpio){
    char pin[4];  
    int fd,len;  

    fd = open("/sys/class/gpio/export", O_WRONLY);
    if (fd < 0) {
        perror("open export");
        return(-1);
    }
    len = sprintf(pin, "%d", gpio->pin);  
    dbg_info("gpio_export=>pin = gpio%s\n",pin);
    if (write(fd, pin, len) < 0) {  
        perror("write export error for pin");
        return -1;  
    }  
    close(fd);  
    return 0;  

}

int gpio_unexport(GPIO* gpio)
{
   char pin[4];  
    int len;  
    int fd;  
  
    fd = open("/sys/class/gpio/unexport", O_WRONLY);  
    if (fd < 0) {  
        perror("open unexport");
        return -1;  
    }  
    len = sprintf(pin, "%d", gpio->pin);
    dbg_info("gpio_unexport=>pin=%s\n",pin);
    if (write(fd, pin, len) < 0) {  
        perror("write unexport");
        return -1;  
    }  
    close(fd);  
    return 0; 
}

int gpio_read(GPIO* gpio, char* value)
{
    char path[64];
    char value_str[4];
    int fd,value1;
  
    sprintf(path, "/sys/class/gpio/gpio%d/value", gpio->pin);  
    dbg_info("value path: %s\n", path);
    fd = open(path, O_RDONLY);
		if (fd < 0) {  
			perror("open value");  
			return -1;  
		}
    if (read(fd, value_str, 3) < 0) {  
        perror("read value");
        return -1;
    }
    sscanf(value_str,"%d",&gpio->value);
    sscanf(value,"%d",&value1);
    dbg_info("value_read = %d\n",gpio->value);
    dbg_info("value_cmd = %d\n",value1);
//	if(gpio->value != value1)
//		gpio->flags |= ERROR;
    close(fd);
    return 0;
}

int gpio_direction(GPIO * gpio)
{
    char path[64];  
    int fd,res;
    char *dir;
    if(gpio->flags & IN)
		dir = "in";
	if(gpio->flags & OUT)
		dir = "out";
    sprintf(path,"/sys/class/gpio/gpio%d/direction", gpio->pin);
	
    dbg_info("direction path: %s,direction = %s\n", path, dir);  
    
    fd = open(path, O_WRONLY);
    if (fd < 0) {
		perror("open direction");
        return -1;  
    }  
	res = write(fd, dir, sizeof(dir));
    if (res <= 0) {
        perror("write direction");
        return -1;
    }
    close(fd);
    return 0;
}

int gpio_write(GPIO* gpio, char* value)
{
    char path[64];  
    int fd;  

    sprintf(path, "/sys/class/gpio/gpio%d/value", gpio->pin);
    
    fd = open(path, O_RDWR);
		if (fd < 0) {  
			perror("open value");  
			return -1;  
		}
	
    int res = write(fd, value, sizeof(value));
    dbg_info("gpio_write value path: %s, value = %s\n ret:5d", path,value,res); 
    if (res <= 0) {
        perror("write value");
        return -1;
    }
    close(fd);  
    return 0;  
}
